#include"thread.h"

int recvnW(int sockfd, void *buf, int length,int fd){
    int total = 0;
    char *p = (char *)buf;
    while(total < length){
        ssize_t sret = recv(sockfd,p+total,length-total,MSG_WAITALL);
        printf("p = %s\n",p);
        total += sret;
    }
    int ret=write(fd,p,length);
    ERROR_CHECK(ret,-1,"write");
    return 0;
}
int serrecv(const int netfd,MYSQL* mysql,sharInfo_t* info)
{  
    train_t train;
    char query[1024]={0};
    char filename[1024]={0};
    char cwd[1024]={0};
    char md5[4096]={0};
    char path[4096]={0};
    int ret;
    bzero(&train,sizeof(train));
    recv(netfd,&train.length,sizeof(int),MSG_WAITALL);
    recv(netfd,&train.buf,train.length,MSG_WAITALL);
    remove_trailing_invisible_chars(train.buf);
    strcpy(filename,train.buf);
    printf("filename = %s\n",filename);

    bzero(&train,sizeof(train));
    recv(netfd,&train.length,sizeof(int),MSG_WAITALL);
    recv(netfd,train.buf,train.length,MSG_WAITALL);
    remove_trailing_invisible_chars(train.buf);
    strcpy(md5,train.buf);
    printf("md5 = %s\n",md5);

    sprintf(query, "SELECT ID FROM df_mes WHERE md5 = '%s' ;",md5);
    mysql_query(mysql,query);
    MYSQL_RES* result=mysql_store_result(mysql);

    getcwd(cwd,sizeof(cwd));
    get_pwd(info,mysql,path);
    strcat(path,filename);
    strcat(cwd,"/storge/");
    strcat(cwd,md5);

    printf("filename = %s\n",path);

    int row=mysql_num_rows(result);

    mysql_free_result(result);
    if(row==0){
        ret=-1;
        send(netfd,&ret,sizeof(int),MSG_NOSIGNAL);
        bzero(&train,sizeof(train));
        recv(netfd,&train.length,sizeof(int),MSG_WAITALL);
        printf("fileLen = %d\n",train.length);

        int fd=open(cwd,O_RDWR|O_CREAT|O_EXCL,0666);


        bzero(query,sizeof(query));
        sprintf(query, "insert into df_mes(fileName,path,user,parID,md5,tomb) values('%s','%s','%s',%d,'%s',0);",filename,path,info->user,info->parentID,md5);
        printf("query = %s\n",query);
        mysql_query(mysql,query);
        result=mysql_store_result(mysql);
        recvnW(netfd,train.buf,train.length,fd);
        mysql_free_result(result);

        train.length=0;
        send(netfd,&train.length,sizeof(int),MSG_NOSIGNAL);
        close(fd);
        return 0;
        
    }
    bzero(&train,sizeof(train));
    train.length=0;
    send(netfd,&train.length,sizeof(int),MSG_NOSIGNAL);
    bzero(query,sizeof(query));
    sprintf(query, "insert into df_mes(fileName,path,user,parID,md5,tomb) values('%s','%s','%s',%d,'%s',0);",filename,path,info->user,info->parentID,md5); 
    mysql_query(mysql,query);

    result=mysql_store_result(mysql);

    mysql_free_result(result);
    return 0;
}
